﻿<!DOCTYPE html>
<!--[if IE]><![endif]-->
<html>
  
  <head>
    <!-- Global site tag (gtag.js) - Google Analytics -->
    <script async="" src="https://www.googletagmanager.com/gtag/js?id=UA-39155502-5"></script>
    <script>
      window.dataLayer = window.dataLayer || [];
      function gtag(){dataLayer.push(arguments);}
      gtag('js', new Date());
  
      gtag('config', 'UA-39155502-5');
    </script>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <title>Update without retrieving | MongoDB.Entities </title>
    <meta name="viewport" content="width=device-width">
    <meta name="title" content="Update without retrieving | MongoDB.Entities ">
    <meta name="generator" content="docfx 2.58.4.0">
    <meta name="description" content="A data access library for MongoDB with an elegant api, LINQ support and built-in entity relationship management.">
    <link rel="shortcut icon" href="../images/favicon.ico">
    <link rel="stylesheet" href="../styles/docfx.vendor.css">
    <link rel="stylesheet" href="../styles/docfx.css">
    <link rel="stylesheet" href="../styles/main.css">
    <meta property="docfx:navrel" content="../toc.html">
    <meta property="docfx:tocrel" content="toc.html">
    
    <meta property="docfx:rel" content="../">
    <meta property="docfx:newtab" content="true">
    <meta property="og:title" content="MongoDB.Entities">
    <meta property="og:site_name" content="MongoDB.Entities">
    <meta property="og:url" content="https://mongodb-entities.com">
    <meta property="og:description" content="A data access library for MongoDB with an elegant api, LINQ support and built-in entity relationship management,">
    <meta property="og:type" content="website">
    <meta property="og:image" content="https://mongodb-entities.com/images/social-square.png">  
  </head>
  <body data-spy="scroll" data-target="#affix" data-offset="120">
    <div id="wrapper">
      <header>
        
        <nav id="autocollapse" class="navbar navbar-inverse ng-scope" role="navigation">
          <div class="container">
            <div class="navbar-header">
              <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#navbar">
                <span class="sr-only">Toggle navigation</span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
              </button>
              
              <a class="navbar-brand" href="../index.html">
                <img id="logo" class="svg" src="../images/icon.png" alt="">
              </a>
            </div>
            <div class="collapse navbar-collapse" id="navbar">
              <form class="navbar-form navbar-right" role="search" id="search">
                <div class="form-group">
                  <input type="text" class="form-control" id="search-query" placeholder="Search" autocomplete="off">
                </div>
              </form>
            </div>
          </div>
        </nav>
        
        <div class="subnav navbar navbar-default">
          <div class="container hide-when-search" id="breadcrumb">
            <ul class="breadcrumb">
              <li></li>
            </ul>
          </div>
        </div>
      </header>
      <div class="container body-content">
        
        <div id="search-results">
          <div class="search-list">Search Results for <span></span></div>
          <div class="sr-items">
            <p><i class="glyphicon glyphicon-refresh index-loading"></i></p>
          </div>
          <ul id="pagination" data-first="First" data-prev="Previous" data-next="Next" data-last="Last"></ul>
        </div>
      </div>
      <div role="main" class="container body-content hide-when-search">
        
        <div class="sidenav hide-when-search">
          <a class="btn toc-toggle collapse" data-toggle="collapse" href="#sidetoggle" aria-expanded="false" aria-controls="sidetoggle">Show / Hide Table of Contents</a>
          <div class="sidetoggle collapse" id="sidetoggle">
            <div id="sidetoc"></div>
          </div>
        </div>
        <div class="article row grid-right">
          <div class="col-md-10">
            <article class="content wrap" id="_content" data-uid="">
<h1 id="update-without-retrieving">Update without retrieving</h1>

<p>you can update a single or batch of entities on the mongodb server by supplying a filter criteria and a subset of properties and the data/ values to be set on them as shown below.</p>
<pre><code class="lang-csharp">await DB.Update&lt;Author&gt;()
        .Match(a =&gt; a.Surname == &quot;Stark&quot;)
        .Modify(a =&gt; a.Name, &quot;Brandon&quot;)
        .Modify(a =&gt; a.Surname, &quot;The Broken&quot;)
        .ExecuteAsync();
</code></pre>
<p>specify the filter criteria with a lambda expression using the <code>.Match()</code> method to indicate which entities/documents you want to target for the update. then use multiples of the <code>.Modify()</code> method to specify which properties you want updated with what data. finally call the <code>.ExecuteAsync()</code> method to run the update command which will take place remotely on the database server.</p>
<h2 id="update-by-id">Update by ID</h2>
<p>if you'd like to update a single entity, simply target it by <code>ID</code> like below:</p>
<pre><code class="lang-csharp">await DB.Update&lt;Author&gt;()
        .MatchID(&quot;xxxxxxxxxxx&quot;)
        .Modify(a =&gt; a.Surname, &quot;The Broken&quot;)
        .ExecuteAsync();
</code></pre>
<h2 id="update-by-matching-with-filters">Update by matching with filters</h2>
<p>you can use <a href="https://mongodb.github.io/mongo-csharp-driver/2.11/apidocs/html/Methods_T_MongoDB_Driver_FilterDefinitionBuilder_1.htm"><em>filter definition builder</em></a> methods to match entities. all of the filters of the official driver are available for use as follows.</p>
<pre><code class="lang-csharp">await DB.Update&lt;Author&gt;()
        .Match(f=&gt; f.Eq(a=&gt;a.Surname,&quot;Stark&quot;) &amp; f.Gt(a=&gt;a.Age,35))
        .Modify(a =&gt; a.Name, &quot;Brandon&quot;)
        .ExecuteAsync();
</code></pre>
<h2 id="update-with-builder-methods">Update with builder methods</h2>
<p>also you can use all the <a href="https://mongodb.github.io/mongo-csharp-driver/2.11/apidocs/html/Methods_T_MongoDB_Driver_UpdateDefinitionBuilder_1.htm"><em>update definition builder</em></a> methods supplied by the mongodb driver like so:</p>
<pre><code class="lang-csharp">await DB.Update&lt;Author&gt;()
        .Match(a =&gt; a.ID == &quot;xxxxxxx&quot;)
        .Modify(x =&gt; x.Inc(a =&gt; a.Age, 10))
        .Modify(x =&gt; x.Set(a =&gt; a.Name, &quot;Brandon&quot;))
        .Modify(x =&gt; x.CurrentDate(a =&gt; a.ModifiedOn))
        .ExecuteAsync();
</code></pre>
<h2 id="update-all-properties">Update all properties</h2>
<p>instead of specifying each and every property with <code>.Modify()</code> you can simply supply a complete entity using <code>.ModifyWith()</code>. all properties of the matched documents will be updated with the corresponding property values of the supplied entity instance.</p>
<pre><code class="lang-csharp">await DB.Update&lt;Book&gt;()
        .MatchID(&quot;xxxxxxxxxxxxx&quot;)
        .ModifyWith(book)
        .ExecuteAsync();
</code></pre>
<h2 id="update-only-a-few-specified-properties">Update only a few specified properties</h2>
<p>you can specify a couple of properties to be updated with the corresponding values from a supplied entity instance like below.</p>
<pre><code class="lang-csharp">await DB.Update&lt;Book&gt;()
        .MatchID(&quot;xxxxxxxxxxxxx&quot;)
        .ModifyOnly(b =&gt; new { b.Title, b.Price }, book)
        .ExecuteAsync();  
</code></pre>
<p>in the above example, only the <code>Title</code> and <code>Price</code> of the matched book will be updated in the database.</p>
<h2 id="update-all-others-except-for-the-specified-properties">Update all others except for the specified properties</h2>
<p>you can update all other properties than the specified properties with the corresponding values from the supplied entity instance like so:</p>
<pre><code class="lang-csharp">await DB.Update&lt;Book&gt;()
        .MatchID(&quot;xxxxxxxxxxxxx&quot;)
        .ModifyExcept(b =&gt; new { b.Price, b.ISBN }, book)
        .ExecuteAsync();  
</code></pre>
<p>in the above example, all other properties except the <code>Price</code> and <code>ISBN</code> are updated with the values from the book instance.</p>
<h1 id="bulk-updates">Bulk updates</h1>
<pre><code class="lang-csharp">var bulkUpdate = DB.Update&lt;Author&gt;();

bulkUpdate.Match(a =&gt; a.Age &gt; 25)
          .Modify(a =&gt; a.Age, 35)
          .AddToQueue();

bulkUpdate.Match(a =&gt; a.Sex == &quot;Male&quot;)
          .Modify(a =&gt; a.Sex, &quot;Female&quot;)
          .AddToQueue();

await bulkUpdate.ExecuteAsync();
</code></pre>
<p>first get a reference to a <code>Update&lt;T&gt;</code> class. then specify matching criteria with <code>Match()</code> method and modifications with <code>Modify()</code> method just like you would with a regular update. then instead of calling <code>ExecuteAsync()</code>, simply call <code>AddToQueue()</code> in order to queue it up for batch execution. when you are ready to commit the updates, call <code>ExecuteAsync()</code> which will issue a single <code>bulkWrite</code> command to the database.</p>
<h1 id="update-and-retrieve">Update and retrieve</h1>
<p>in order to update an entity and retrieve the updated enity, use the <code>.UpdateAndGet&lt;T&gt;()</code> method on the <code>DB</code> class like so:</p>
<pre><code class="lang-csharp">var result = await DB.UpdateAndGet&lt;Book&gt;()
                     .Match(b =&gt; b.ID == &quot;xxxxxxxxxxxxx&quot;)
                     .Modify(b =&gt; b.Title, &quot;updated title&quot;)
                     .ExecuteAsync();
</code></pre>
<h2 id="update-and-retrieve-with-projection">Update and retrieve with projection</h2>
<p>projection of the returned entity is possible using the <code>.Project()</code> method before calling <code>.ExecuteAsync()</code>.</p>
<pre><code class="lang-csharp">var result = await DB.UpdateAndGet&lt;Book&gt;()
                     .Match(b =&gt; b.ID == &quot;xxxxxxxxxxxxx&quot;)
                     .Modify(b =&gt; b.Title, &quot;updated title&quot;)
                     .Project(b =&gt; new Book { Title = b.Title })
                     .ExecuteAsync();
</code></pre>
<p>you can also project the result to a completely different type using the generic overload like so:</p>
<pre><code class="lang-csharp">var result = await DB.UpdateAndGet&lt;Book, decimal&gt;()
                     .Match(b =&gt; b.ID == &quot;xxxxxxxxxxxxx&quot;)
                     .Modify(b =&gt; b.Title, &quot;updated title&quot;)
                     .Project(b =&gt; b.Price)
                     .ExecuteAsync();
</code></pre>
<h1 id="aggregation-pipeline-updates">Aggregation pipeline updates</h1>
<p>starting from mongodb sever v4.2, we can refer to existing fields of the documents when updating as described <a href="https://docs.mongodb.com/master/reference/command/update/index.html#update-with-aggregation-pipeline">here</a>.</p>
<p>the following example does 3 things.</p>
<ul>
<li>creates a 'FullName' field by concatenating the values from 'FirstName' and 'LastName' fields.</li>
<li>creates a 'LowerCaseEmail' field by getting the value from 'Email' field and lower-casing it.</li>
<li>removes the Email field.</li>
</ul>
<pre><code class="lang-csharp">await DB.Update&lt;Author&gt;()
        .Match(_ =&gt; true)
        .WithPipelineStage(&quot;{ $set: { FullName: { $concat: ['$FirstName',' ','$LastName'] }}}&quot;)
        .WithPipelineStage(&quot;{ $set: { LowerCaseEmail: { $toLower: '$Email' } } }&quot;)
        .WithPipelineStage(&quot;{ $unset: 'Email'}&quot;)
        .ExecutePipelineAsync();
</code></pre>
<p><strong>note:</strong> pipeline updates and regular updates cannot be used together in one command as it's not supported by the official c# driver.</p>
<h1 id="array-filter-updates">Array filter updates</h1>
<pre><code class="lang-csharp">await DB.Update&lt;Book&gt;()
        .Match(_ =&gt; true)
        .WithArrayFilter(&quot;{ 'x.Age' : { $gte : 30 } }&quot;)
        .Modify(&quot;{ $set : { 'Authors.$[x].Age' : 25 } }&quot;)
        .ExecuteAsync();
</code></pre>
<p>the above update command will set the age of all authors of books where the age is 30 years or older to 25. refer to <a href="https://docs.mongodb.com/manual/reference/operator/update/positional-filtered/">this document</a> for more info on array filters.</p>
</article>
          </div>
          
          <div class="hidden-sm col-md-2" role="complementary">
            <div class="sideaffix">
              <div class="contribution">
                <ul class="nav">
                </ul>
              </div>
              <nav class="bs-docs-sidebar hidden-print hidden-xs hidden-sm affix" id="affix">
                <h5>In This Article</h5>
                <div></div>
              </nav>
            </div>
          </div>
        </div>
      </div>
      
      <footer>
        <div class="grad-bottom"></div>
        <div class="footer">
          <div class="container">
            <span class="pull-right">
              <a href="#top">Back to top</a>
            </span>
            Developed by <a href='https://github.com/dj-nitehawk'>Đĵ ΝιΓΞΗΛψΚ</a> and <a href='https://github.com/dj-nitehawk/MongoDB.Entities/graphs/contributors'>contributors</a> / Licensed under <a href='https://github.com/dj-nitehawk/MongoDB.Entities/blob/master/LICENSE'>MIT</a> / Website generated by <a href='https://dotnet.github.io/docfx/'>DocFX</a>
            
          </div>
        </div>
      </footer>
    </div>
    
    <script type="text/javascript" src="../styles/docfx.vendor.js"></script>
    <script type="text/javascript" src="../styles/docfx.js"></script>
    <script type="text/javascript" src="../styles/main.js"></script>
  </body>
</html>
